import $ from '../jquery-3.4.1.min.js';
import ajax from '../utils/ajax.js';
import {
    showCommunityName,
    showAllClassName,
    getAllPaySet
} from './paySet.js'
//默认全局搜索
const searchData = {
    value: ""
}
let {
    nowPage,//当前页面
    pageSize,//当前页面显示多少条数据
    total,//总共多少数据
    pages,//总共页数
    nowPageSize//当前页面实际多少数据

} = {
    nowPage: 1,//当前页面
    pageSize: 3,//当前页面显示多少条数据
    total: 0,//总共多少数据
    pages: 0,//总共页数
    nowPageSize: 0
}

/* 新增 */

$(`#formData`).click(function (e) {
    $(`#formDataModal`).show();
    showCommunityName(`#F_commtiy_select`);
    showAllRoom();
    showAllClassName(`#tableForm_ul li`, `#form_class_select`);
    showAllPaySetName(`#form_paySetName`)
})
//改变事件
$(`#form_class_select`).change(async function (e) {
    const payClassName = $(this).val();
    searchData.value = payClassName
    showFliterPaySetName(`#form_paySetName`);

})
$(`#formChange_class_select`).change(async function (e) {
    const payClassName = $(this).val();
    searchData.value = payClassName
    showFliterPaySetName(`#formChange_paySetName`);

})
$(`#formChange_paySetName`).change(function (e) {
    const price = $("#formChange_paySetName option:selected").data("price")
    $(`#formchange_paySetPrice`).val(price)
})
$(`#form_paySetName`).change(function (e) {
    const price = $("#form_paySetName option:selected").data("price")
    $(`#form_paySetPrice`).val(price)
})
//算出总数 止度-起度
$(`.model-ul`).on(`keyup`, `.keyUp`, function (e) {
    const count = $(`#startKey`).val()
    const count1 = $(`#endKey`).val()
    const total = count1 - count
    $(`#count`).val(total)
})
$(`.model-ul`).on(`keyup`, `.keyUp`, function (e) {
    const count = $(`#change_startKey`).val()
    const count1 = $(`#change_endKey`).val()
    const total = count1 - count
    const price = $(`#formchange_paySetPrice`).val();
    const shouldPay = (price * total).toFixed(2)
    $(`#shouldPay`).val(shouldPay)
    $(`#change_count`).val(total)
})
//确认新增 
$(`#form_sureBtn`).click(function (e) {

    const communtiyId = $(`#F_commtiy_select`).val();
    const room = $(`#roomId`).val();
    const setNameId = $(`#form_paySetName`).val();
    const count = $(`#count`).val();
    const time = new Date().toLocaleString();
    const paySetPrice = $(`#form_paySetPrice`).val();
    const shouldPay = (count * paySetPrice).toFixed(2);
    if (count <= 0 || shouldPay == "NaN") {
        alert(`起度与止度不能为0或者未选择项目标准`)
        return
    }
    const prestore = $(`#prestore`).val();
    const startKey = $(`#startKey`).val();
    const endKey = $(`#endKey`).val();

    const chargeState = $(`#chargeState`).val();
    const data = { communtiyId, room, setNameId, count, time, startKey, endKey, shouldPay, prestore, chargeState }

    ajax({
        url: `/payTypeIn/addpayTypIn`,
        type: `POST`,
        data: data,
        success(res) {
            if (res.code == 200) {
                alert(`新增成功`)
                searchData.value = ""
                showFliterTypeIn();

            } else {
                alert(`类别已有或服务器处理失败`)
            }
        }
    })
    $(`#formDataModal`).hide();

    // console.log(data);
})
//确认修改
$(`#changeform_sureBtn`).click(async function (e) {


    $(`#change_formDataModal`).hide();
    const _id = $(`#storageId`).val();
    const communtiyId = $(`#F_changeCommtiy_select`).val();
    const room = $(`#change_roomId`).val();
    const setNameId = $(`#formChange_paySetName`).val();
    const count = $(`#change_count`).val();
    const time = new Date().toLocaleString();
    const paySetPrice = $(`#formchange_paySetPrice`).val();
    const shouldPay = (count * paySetPrice).toFixed(2);
    if (count <= 0 || shouldPay == "NaN") {
        alert(`起度与止度不能为0或者未选择项目标准`)
        return
    }
    const prestore = $(`#change_prestore`).val();
    const startKey = $(`#change_startKey`).val();
    const endKey = $(`#change_endKey`).val();

    const chargeState = $(`#change_chargeState`).val();
    const data = { communtiyId, room, setNameId, count, time, startKey, endKey, shouldPay, prestore, chargeState, _id }

    console.log(`准备修改的值------------`, data, _id);
    ajax({
        url: `/payTypeIn/changeTypIn`,
        type: `POST`,
        data: data,
        success(res) {
            if (res.code == 200) {
                alert(`修改成功`)
                searchData.value = ""
                showFliterTypeIn();
            } else if (res.code == 500) {
                alert(`类别已有或服务器处理失败`)
            }
        }
    })
})
function sendChangeData(data, renderFoo, url) {

    return new Promise((resolve, reject) => {
        ajax({
            url: url,
            type: `POST`,
            data: data,
            success(res) {
                if (res.code == 200) {

                    renderFoo();
                    if (nowPageSize == 1) {
                        nowPage--
                        renderFoo();
                    }
                    resolve(res);
                } else {
                    alert(`操作失败`);
                }
            }

        })
    })

}



//显示单价

/* 得到数据================================================ */

function getFliterPaySet() {
    return new Promise((resolve, reject) => {
        ajax({
            url: `/paySet/getpaySet`,
            type: `POST`,
            data: {
                ...searchData,
                nowPage,
                pageSize
            },
            success(res) {
                if (res.code == 200) {
                    resolve(res);
                    // console.log(`从后端返回的收费项目标准-------------`, res);
                } else {
                    $(`#form_paySetName`).val(`暂无此数据`)
                    // alert(`暂无此数据 请先新增`);
                    console.log(`收费标准数据库暂无数据请先新增`);
                }
            }
        })
    })
}
//得到所有的抄表录入
function getAllTyenIn() {

}
//得到筛选的抄表录入
function getFliterTypeIn() {
    return new Promise((resolve, reject) => {
        ajax({
            url: `/payTypeIn/getTypIn`,
            type: `POST`,
            data: {
                ...searchData,
                nowPage,
                pageSize
            },
            success(res) {
                if (res.code == 200) {
                    // total = res.total;//当前的总数据
                    resolve(res);
                    // console.log(`从后端返回的typein类型-------------`, res);
                } else {
                    // alert(`数据库暂无数据 请先新增`);
                    console.log(`项目名称数据暂无数据请先新增`);
                }
            }
        })
    })
}
//得到需要修改的值
function getChangeTyeIn(_id) {
    return new Promise((resolve, reject) => {
        ajax({
            url: `/payTypeIn/findTypIn`,
            type: `POST`,
            data: { _id },
            success(res) {
                if (res.code == 200) {
                    resolve(res)
                    // $(`#F_changeCommtiy_select`).val(res.data[0].communtiyId.communityName)
                    // console.log(`获取到修改这条的所有数据·······`, res);
                } else {
                    alert(`查无此数据`)
                }
            }
        })
    })
}
//得到所有的房号
function getAllRoom() {
    return new Promise((resolve, reject) => {
        ajax({
            url: '/owner',
            type: 'GET',
            success(res) {
                resolve(res)
                console.log(`home====================================`, res);


                // defaultHomeNumber(res.result)
            }
        })
    })
}





/* 渲染数据================================================ */

//渲染 标准名称下拉框
function renderSetNameSelect(res, tag) {
    const data = res.data
    const option = data.map(item => {
        return `<option value="${item._id}" data-price="${item.paySetPrice}">${item.paySetName}</option>`
    }).join(``);
    $(tag).html(option);
    if (data.length === 1) {
        $(`#form_paySetPrice`).val(data[0].paySetPrice)
    }
}
//渲染表格
function renderTable(res) {
    const data = res.data

    const html = data.map(item => {
        return `<tr>
        <td>
        <input type="checkbox" name="" id="">
        </td>
        <td>${item.communtiyId ? item.communtiyId.communityName : `该小区已被删除`}</td>
        <td>${item.room ? item.room.ownerHomeNumber : `改房号被删除`}</td>
        <td>${item.setNameId ? item.setNameId.payClassName : `该项目名称被删除`}</td>
        <td>${item.setNameId ? item.setNameId.paySetName : `该项目标准被删除`}</td>
        <td>${item.time}</td>
        <td>${item.setNameId ? item.setNameId.paySetPrice : `该单价被删除`}</td>
        <td>${item.startKey}</td>
        <td>${item.endKey}</td>
        <td>${item.endKey - item.startKey}</td>
        <td>${item.shouldPay}</td>
        <td>${item.chargeState}</td>
        <td>${item.prestore}</td>
        <td>
            <span data-id="${item._id}">编辑</span>
            <span data-id="${item._id}">删除</span>
        </td>
        </tr>`
    }).join(``);
    $(`#typeIn_tbody`).html(html)

    pages = res.pages;//当前的总页数
    let li = ``;
    for (let i = 1; i <= pages; i++) {
        li = li + `<li>${i}</li>`
    }
    $(`#tableForm_ul`).html(li);
}
// 渲染房号
function defaultHomeNumber(data) {
    const html = data.map(item => (
        `
        <option value="${item._id}">${item.ownerHomeNumber}</option>
        `
    )).join('')
    $('#roomId').html(html)
    $('#change_roomId').html(html)
}





/* 展示数据================================================ */
showFliterTypeIn();
showAllRoom();
//展示房号
async function showAllRoom() {
    const { data } = await getAllRoom();
    defaultHomeNumber(data)
}
//展示所有标准项目下拉框
async function showAllPaySetName(tag) {
    const res = await getAllPaySet();
    renderSetNameSelect(res, tag);
}

//展示筛选的标准项目下拉框
async function showFliterPaySetName(tag) {
    const res = await getFliterPaySet();
    renderSetNameSelect(res, tag);
}

//展示筛选的表格
async function showFliterTypeIn() {
    const res = await getFliterTypeIn();
    renderTable(res);
    $(`#tableForm_ul li`).prop(`class`, ``);
    // console.log(nowPage);
    $(`#tableForm_ul li`).eq(nowPage * 1 - 1).prop(`class`, `pageListActive`);
    nowPageSize = res.data.length;
}

/* 页码展示 */


//下一页
$(`#typeIn_next`).click(function (params) {
    if (nowPage < pages) {
        nowPage++;
        // $(checkBtn).prop(`checked`, false)
        showFliterTypeIn();
    }
})
//上一页
$(`#typeIn_previous`).click(function (e) {
    if (nowPage > 1) {
        nowPage--
        // $(checkBtn).prop(`checked`, false)
        showFliterTypeIn()
    }
})
//搜索
$(`#typeIn_search`).on(`click`, function (e) {
    const value = $(`#typeIn_input`).val();
    searchData.value = value;
    // $(checkBtn).prop(`checked`, false)
    showFliterTypeIn();
})
//点击
$(`#tableForm_ul`).on(`click`, `li`, function (e) {
    nowPage = $(this).text();
    showFliterTypeIn();
})
//改变
$(`#typeIn_change`).change(function (params) {
    pageSize = $(this).val();
    nowPage = 1;
    // $(checkBtn).prop(`checked`, false)
    showFliterTypeIn();
})

/* 修改 删除 */
function delAjax(url, data, foo) {
    ajax({
        url: url,
        type: `POST`,
        data: data,
        success(res) {
            if (res.code == 200) {
                foo();
                if (nowPageSize == 1) {
                    nowPage--
                    foo();

                }
                if (res.total == 0) {
                    alert(`数据删完了哦`)
                    location.reload();
                }
            } else {
                alert(`操作失败`);
            }
        }

    })
}

$(`#typeIn_tbody`).on(`click`, `span`, async function (e) {
    const key = $(this).text();
    const _id = $(this).data(`id`);
    switch (key) {
        case `编辑`:
            showCommunityName(`#F_changeCommtiy_select`);
            showAllClassName(`#tableForm_ul li`, `#formChange_class_select`);
            showAllPaySetName(`#formChange_paySetName`);

            $(`#change_formDataModal`).show();
            const res = await getChangeTyeIn(_id);
            // console.log(res);
            $(`#F_changeCommtiy_select`).val(res.data[0].communtiyId._id);
            $(`#formChange_class_select`).val(res.data[0].setNameId.payClassName);
            $(`#change_startKey`).val(res.data[0].startKey);
            $(`#change_endKey`).val(res.data[0].endKey);
            $(`#change_count`).val(res.data[0].count);
            $(`#shouldPay`).val(res.data[0].shouldPay);
            $(`#change_chargeState`).val(res.data[0].chargeState);
            $(`#change_prestore`).val(res.data[0].prestore);
            $(`#storageId`).val(_id)

            break;
        case `删除`:
            const data = { _id };
            delAjax(`/payTypeIn/delTypIn`, data, showFliterTypeIn)
            break;

        default:

            break;
    }

})








